package com.wql.fileupload;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.activation.MimetypesFileTypeMap;

/**
 * @author wuqinglong
 * @date 2014年12月17日 下午9:27:33
 */
public class FileUpload {

	private static final String BOUNDARY = "---------------------------123821742118716";

	/**
	 * 文件上传
	 * 
	 * @param filePath
	 * @param fileName
	 * @param urlStr
	 * @return
	 */
	public static String upload(String filePath, String fileName, String urlStr) {
		File file = new File(filePath);
		if (!file.isFile() || null == urlStr || urlStr.isEmpty())
			return "param error";
		if (null == fileName || fileName.isEmpty())
			fileName = file.getName();
		try {
			URL url = new URL(urlStr);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setRequestMethod("POST");
			connection.addRequestProperty("FileName", fileName);
			connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
			writeFile(file, BOUNDARY, new BufferedOutputStream(connection.getOutputStream()));
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			StringBuilder sb = new StringBuilder("");
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			return sb.toString().replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}

	/**
	 * 文件上传
	 * 
	 * @param filePath
	 * @param urlStr
	 * @return
	 */
	public static String upload(String filePath, String urlStr) {
		return upload(filePath, null, urlStr);
	}

	// 写文件到传输流
	private static void writeFile(File file, String BOUNDARY, BufferedOutputStream out) throws IOException, FileNotFoundException {
		String filename = file.getName();
		String contentType = new MimetypesFileTypeMap().getContentType(file);
		if (filename.endsWith(".png")) {
			contentType = "image/png";
		}
		if (contentType == null || contentType.equals("")) {
			contentType = "application/octet-stream";
		}
		StringBuffer strBuf = new StringBuffer();
		strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
		strBuf.append("Content-Disposition: form-data; name=\"" + "wqinglong" + "\"; filename=\"" + filename + "\"\r\n");
		strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
		out.write(strBuf.toString().getBytes());
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		in.close();
		byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
		out.write(endData);
		out.flush();
		out.close();
	}
}
